package com.tfswue.lhj.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tfswue.lhj.common.PageQuery;
import com.tfswue.lhj.common.Result;
import com.tfswue.lhj.dto.UserDTO;
import com.tfswue.lhj.service.UserService;
import com.tfswue.lhj.vo.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户控制器
 * 
 * @author daygods
 * @since 2025-07-09
 */
@Slf4j
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
@Tag(name = "用户管理", description = "用户相关接口")
public class UserController {
    
    private final UserService userService;
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "新用户注册")
    public Result<Boolean> register(@Valid @RequestBody UserDTO userDTO) {
        try {
            boolean result = userService.register(userDTO);
            return Result.success(result, "注册成功");
        } catch (Exception e) {
            log.error("用户注册失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录验证")
    public Result<UserVO> login(
            @Parameter(description = "用户名") @RequestParam String username,
            @Parameter(description = "密码") @RequestParam String password,
            HttpServletRequest request) {
        try {
            String loginIp = getClientIp(request);
            UserVO userVO = userService.login(username, password, loginIp);
            return Result.success(userVO, "登录成功");
        } catch (Exception e) {
            log.error("用户登录失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 分页查询用户列表
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询用户", description = "分页查询用户列表")
    public Result<IPage<UserVO>> getUserPage(PageQuery pageQuery) {
        IPage<UserVO> page = userService.getUserPage(pageQuery);
        return Result.success(page);
    }
    
    /**
     * 根据ID获取用户详情
     */
    @GetMapping("/{userId}")
    @Operation(summary = "获取用户详情", description = "根据用户ID获取用户详情")
    public Result<UserVO> getUserById(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        UserVO userVO = userService.getUserById(userId);
        if (userVO == null) {
            return Result.error("用户不存在");
        }
        return Result.success(userVO);
    }
    
    /**
     * 创建用户
     */
    @PostMapping
    @Operation(summary = "创建用户", description = "创建新用户")
    public Result<Boolean> createUser(@Valid @RequestBody UserDTO userDTO) {
        try {
            boolean result = userService.createUser(userDTO);
            return Result.success(result, "创建成功");
        } catch (Exception e) {
            log.error("创建用户失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/{userId}")
    @Operation(summary = "更新用户", description = "更新用户信息")
    public Result<Boolean> updateUser(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Valid @RequestBody UserDTO userDTO) {
        try {
            boolean result = userService.updateUser(userId, userDTO);
            return Result.success(result, "更新成功");
        } catch (Exception e) {
            log.error("更新用户失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{userId}")
    @Operation(summary = "删除用户", description = "删除指定用户")
    public Result<Boolean> deleteUser(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        try {
            boolean result = userService.deleteUser(userId);
            return Result.success(result, "删除成功");
        } catch (Exception e) {
            log.error("删除用户失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新用户状态
     */
    @PutMapping("/{userId}/status")
    @Operation(summary = "更新用户状态", description = "更新用户状态")
    public Result<Boolean> updateUserStatus(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "状态") @RequestParam Integer status) {
        try {
            boolean result = userService.updateUserStatus(userId, status);
            return Result.success(result, "状态更新成功");
        } catch (Exception e) {
            log.error("更新用户状态失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 重置用户密码
     */
    @PutMapping("/{userId}/reset-password")
    @Operation(summary = "重置密码", description = "重置用户密码")
    public Result<Boolean> resetPassword(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "新密码") @RequestParam String newPassword) {
        try {
            boolean result = userService.resetPassword(userId, newPassword);
            return Result.success(result, "密码重置成功");
        } catch (Exception e) {
            log.error("重置密码失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 修改用户密码
     */
    @PutMapping("/{userId}/change-password")
    @Operation(summary = "修改密码", description = "修改用户密码")
    public Result<Boolean> changePassword(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "旧密码") @RequestParam String oldPassword,
            @Parameter(description = "新密码") @RequestParam String newPassword) {
        try {
            boolean result = userService.changePassword(userId, oldPassword, newPassword);
            return Result.success(result, "密码修改成功");
        } catch (Exception e) {
            log.error("修改密码失败: {}", e.getMessage());
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 检查用户名是否存在
     */
    @GetMapping("/check-username")
    @Operation(summary = "检查用户名", description = "检查用户名是否存在")
    public Result<Boolean> checkUsername(
            @Parameter(description = "用户名") @RequestParam String username) {
        boolean exists = userService.existsUsername(username);
        return Result.success(exists);
    }
    
    /**
     * 检查邮箱是否存在
     */
    @GetMapping("/check-email")
    @Operation(summary = "检查邮箱", description = "检查邮箱是否存在")
    public Result<Boolean> checkEmail(
            @Parameter(description = "邮箱") @RequestParam String email) {
        boolean exists = userService.existsEmail(email);
        return Result.success(exists);
    }
    
    /**
     * 获取最近登录的用户
     */
    @GetMapping("/recent-login")
    @Operation(summary = "最近登录用户", description = "获取最近登录的用户列表")
    public Result<List<UserVO>> getRecentLoginUsers(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") int limit) {
        List<UserVO> users = userService.getRecentLoginUsers(limit);
        return Result.success(users);
    }
    
    /**
     * 获取客户端IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}
